﻿using System.Security.Principal;
using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using MyToDo.Api.Context;
using MyToDo.Shared.Dtos;
using MyToDo.Shared.Extensions;

namespace MyToDo.Api.Service
{
    public class LoginService : ILoginService
    {
        private readonly IUnitOfWork unitOfWork;

        public LoginService(IUnitOfWork unitOfWork, IMapper mapper)
        {
            Mapper = mapper;
            this.unitOfWork = unitOfWork;
        }

        public readonly IMapper Mapper;

        public async Task<ApiResponse> LoginAsync(string account, string password)
        {
            try
            {
                var passwordMD5 = password.GetMD5();
                var repository = unitOfWork.GetRepository<User>();

                var model = await repository.GetFirstOrDefaultAsync(predicate: x =>
                    x.Account.Equals(account) && x.Password.Equals(passwordMD5)
                );
                if (model == null)
                {
                    return new ApiResponse("账户名或者密码错误");
                }
                return new ApiResponse(
                    true,
                    new UserDto()
                    {
                        Account = model.Account,
                        UserName = model.UserName,
                        Id = model.Id,
                    }
                );
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }
        }

        public async Task<ApiResponse> RegisterAsync(UserDto userDto)
        {
            try
            {
                var user = Mapper.Map<User>(userDto);
                var repository = unitOfWork.GetRepository<User>();
                var model = await repository.GetFirstOrDefaultAsync(predicate: x =>
                    x.Account.Equals(user.Account)
                );
                if (model != null)
                    return new ApiResponse($"账户{user.Account}已存在");
                user.Password = userDto.Password.GetMD5();
                var id = SnowflakeIDcreator.nextId().ToString();
                // 雪花算法生成UserId
                user.UserId = id;
                user.CreateId = id;
                await repository.InsertAsync(user);
                if (await unitOfWork.SaveChangesAsync() > 0)
                    return new ApiResponse(true, user);

                return new ApiResponse("添加账户失败");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RegisterAsync has error{ex.Message}");
                return new ApiResponse("注册账户失败");
            }
        }
    }
}
